<?php

namespace app\subscribe\resource;


use think\Event;
use think\facade\Db;
use app\common\repositories\housing\HousingLogRepository;
use app\common\repositories\housing\HousingPictureRepository;

class ResourceSubscribe
{

    /**
     * 房源创建
     * @param $data
     * @return void
     *
     * @author Amos
     * 2024-06-05 16:19
     */
    public function onCreateRoom($data)
    {
        $resourceInfo = $data['resourceInfo'] ?? '';
        $userId = $data['userId'] ?? 0;
        $remark = $data['remark'] ?? '';

        /** @var HousingLogRepository $housingLogRepository */
        $housingLogRepository = app()->make(HousingLogRepository::class);

        $roomLogData['remark'] = $remark . '创建房源';
        $roomLogData['resource_id'] = $resourceInfo['id'];
        $roomLogData['property_id'] = $resourceInfo['property_id'] ?? '0';
        $housingLogRepository->addData($resourceInfo['items_id'], $roomLogData, $userId);
    }

    /**
     * 房源编辑
     * @param $data
     * @return void
     *
     * @author Amos
     * 2024-06-05 16:19
     */
    public function onRedact($data)
    {
        $resourceInfo = $data['resourceInfo'] ?? '';
        $userId = $data['userId'] ?? 0;
        $remark = $data['remark'] ?? '';

        /** @var HousingLogRepository $housingLogRepository */
        $housingLogRepository = app()->make(HousingLogRepository::class);

        $roomLogData['remark'] = $remark . '编辑房源';
        $roomLogData['resource_id'] = $resourceInfo['id'];
        $roomLogData['property_id'] = $resourceInfo['property_id'] ?? '0';
        $housingLogRepository->addData($resourceInfo['items_id'], $roomLogData, $userId);
    }


    /**
     * 监听房源删除
     * @param $data
     * @return void
     *
     * @author Amos
     * 2024-06-05 16:18
     */
    public function onDelete($data)
    {
        $resourceInfo = $data['resourceInfo'] ?? '';
        $userId = $data['userId'] ?? '0';

        # 删除图片记录
        /** @var HousingPictureRepository $pictureRepository */
        $pictureRepository = app()->make(HousingPictureRepository::class);
        $pictureRepository->removePicture($resourceInfo['id']);

        # 删除日志记录
        /** @var HousingLogRepository $housingLogRepository */
        $housingLogRepository = app()->make(HousingLogRepository::class);
        $housingLogRepository->delByHousingId($resourceInfo['id']);
    }


    public function subscribe(Event $event)
    {
        $event->listen('housing.create', [$this, 'onCreateRoom']);## 创建房源
        $event->listen('housing.redact', [$this, 'onRedact']); ## 房源编辑
        $event->listen('housing.delete', [$this, 'onDelete']);## 房源删除
    }
}